package com.bangbang.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.Set;
@Component
@Configurable
@EnableScheduling
public class dingshi {
    @Autowired
    private RedisTemplate redisTemplate;
    //定时方法
    @Scheduled(cron = "* * * * * ?" )
    public boolean dingshi(){

        String numstr = 1 + "-" + "num";
        String timestr = 1 + "-" + "time";
        //获取最近访问的三个标签

        //获取浏览量最高的三个标签，分别设置分数3.2.1
        redisTemplate.boundZSetOps(numstr).removeRangeByScore(0,3);
        Set set = redisTemplate.boundZSetOps(timestr).reverseRange(0, 2);
        Set set2 = redisTemplate.boundZSetOps(numstr).reverseRange(0, 2);
        int i =1;
        Set index2 = redisTemplate.boundZSetOps("index").reverseRange(0, -1);
        for (Object o : set2) {
            if (!index2.contains(o)){
                if (i == 1){
                    String s = JSONObject.toJSONString(o);
                    redisTemplate.boundZSetOps("index").add(o,3);
                }
                if (i == 2){
                    redisTemplate.boundZSetOps("index").add(o,2);

                }
                if (i == 3){
                    redisTemplate.boundZSetOps("index").add(o,1);
                }
                i++;
                if (i == 4){
                    i=0;
                }
            }else {
                Set index = redisTemplate.boundZSetOps("index").reverseRange(0, -1);
                for (Object o2 : set) {
                    String s = JSONObject.toJSONString(o2);
                    boolean contains = index.contains(o2);
                    if (contains){
                        redisTemplate.boundZSetOps("index").incrementScore(o2,3.0);
                        Double index1 = redisTemplate.boundZSetOps("index").score(o2);
                    }else {
                        redisTemplate.boundZSetOps("index").add(o2,3);
                    }
                }
            }

        }

        //将最近访问的加入缓存，如果没有就加入，并分数为3，如果有，就在原来的基础上加3
        System.out.println("每十秒执行一次");
        Set indexf = redisTemplate.boundZSetOps("index").reverseRange(0, -1);
        for (Object o : indexf) {
            Double index1 = redisTemplate.boundZSetOps("index").score(o);
            String s = JSONObject.toJSONString(o);
            System.out.println(o + "的分数" + index1);
            System.out.println(s);
        }
        return true;
    }
}
